//
//  PPSystemConfiguraton.m
//  PetParadise
//
//  Created by 陈无忌 on 8/1/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPSystemConfiguraton.h"


#define USERNAME @"userName"
#define PASSWORD @"userPassWord"
#define AUTOLOGIN @"autoLogin"
#define DISTANCE @"distance"
#define BEACONSTATE @"beaconState"
#define PETAVATAR @"petAvatar"
#define USERAVATAR @"userAvatar"

@implementation PPSystemConfiguraton

static PPSystemConfiguraton *_sharedSystemConfiguration;

-(NSMutableArray *)applyArray
{
    if (!_applyArray) {
        _applyArray = [NSMutableArray array];
    }
    return _applyArray;
}

-(NSMutableArray *)friendArray
{
    if (!_friendArray) {
        _friendArray = [NSMutableArray array];
    }
    return _friendArray;
}

-(NSMutableArray *)petsArray
{
    if (!_petsArray) {
        _petsArray = [NSMutableArray array];
    }
    return _petsArray;
}

-(NSMutableArray *)topicArray
{
    if (!_topicArray) {
        _topicArray = [NSMutableArray array];
    }
    return _topicArray;
}

-(NSMutableArray *)conversationArray
{
    if (!_conversationArray) {
        _conversationArray = [NSMutableArray array];
    }
    return _conversationArray;
}

-(NSMutableArray *)circleArray
{
    if (!_circleArray) {
        _circleArray = [NSMutableArray array];
    }
    return _circleArray;
}

-(NSMutableArray *)keywordArray
{
    if (!_keywordArray) {
        _keywordArray = [NSMutableArray array];
    }
    return _keywordArray;
}


+(void)clearShared
{
    _sharedSystemConfiguration = nil;
}

+(PPSystemConfiguraton *)sharedSystemConfiguration
{
    if (!_sharedSystemConfiguration) {
        _sharedSystemConfiguration = [[super allocWithZone:NULL] init];
    }
    return _sharedSystemConfiguration;
}

+(id) allocWithZone:(NSZone *)zone
{
    return [self sharedSystemConfiguration];
}

-(id) init
{
    if (_sharedSystemConfiguration) {
        return _sharedSystemConfiguration;
    }
    self = [super init];
    if (self) {
        self.userDefault = [NSUserDefaults standardUserDefaults];
    }
    return self;
}

-(void)saveLoginUserName:(NSString*)userName AndPassword:(NSString*)password autoLogin:(BOOL)isAutoLogin
{
    if (userName == nil) {
        userName = @"";
    }
    
    if (password == nil) {
        password = @"";
    }
    
    [self.userDefault setValue:userName forKey:USERNAME];
    [self.userDefault setValue:password forKey:PASSWORD];
    [self.userDefault setBool:isAutoLogin forKey:AUTOLOGIN];
    if (![self.userDefault boolForKey:BEACONSTATE]) {
        [self.userDefault setBool:false forKey:BEACONSTATE];
    }
    if (![self.userDefault floatForKey:DISTANCE]) {
        [self.userDefault setFloat:50.0 forKey:DISTANCE];
    }
    [self.userDefault synchronize];
}


-(void)changeDistance:(float)distance
{
    [self.userDefault setFloat:distance forKey:DISTANCE];
    [self.userDefault synchronize];
    
}

-(void)setBeaconStaus:(BOOL)flag
{
    [self.userDefault setBool:flag forKey:BEACONSTATE];
    [self.userDefault synchronize];
}

-(void)setPetAvatarWithPath:(NSString *)filePath
{
    [self.userDefault setValue:filePath forKey:PETAVATAR];
    [self.userDefault synchronize];
}

-(void)setUserAvatarWithPath:(NSString *)filePath
{
    [self.userDefault setValue:filePath forKey:USERAVATAR];
    [self.userDefault synchronize];
}

-(void)reSetPassWord:(NSString *)password
{
    [self.userDefault setValue:password forKey:PASSWORD];
    [self.userDefault synchronize];
}

- (void)getUserInfowithComepletion:(CompletionBlock)completionBlock
{
    NSString *url = [PPAPIList getAPIList].PPQueryUserMsgByUserId;
    NSDictionary *params = @{@"userId":@(self.userInfo.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation , id responseObject){
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            //返回成功
            NSError *err = nil;
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSDictionary *userDic =resultMap[@"user"];
            self.userInfo = [[PPUserInfo alloc] initWithDictionary:userDic error:&err];
            NSLog(@"我的用户信息已经刷新");
            if (completionBlock) {
                completionBlock();
            }
        }
    }failure:^(AFHTTPRequestOperation *operation,NSError *error){
        NSLog(@"我的用户信息刷新网络终断");
    }];
}

- (void)getUserSettingwithCompletion:(CompletionBlock)completionBlock
{
    NSString *url = [PPAPIList getAPIList].PPGetUserSetting;
    NSDictionary *params = @{@"userId":@(self.userInfo.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *err  = nil;
        NSDictionary *resultMap = responseObject[@"resultMap"];
        NSDictionary *settingDic = resultMap[@"userSetting"];
        self.userSetting = [[PPUserSetting alloc] initWithDictionary:settingDic error:&err];
        NSLog(@"我的用户设置已经刷新");
        if (completionBlock) {
            completionBlock();
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"我的用户设置刷新网络终断");
    }];
    
}


- (void)getFriendListwithComepletion:(CompletionBlock)completionBlock
{
    NSString *url = [PPAPIList getAPIList].PPQueryFriendByUserId;
    NSDictionary *params = @{@"userId":@(self.userInfo.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation , id responseObject){
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            //返回成功
            [self.friendArray removeAllObjects];
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSArray *friendList = resultMap[@"friendList"];
            self.friendArray = [PPUserInfo arrayOfModelsFromDictionaries:friendList];
            NSLog(@"我的好友已经刷新");
            if (completionBlock) {
                completionBlock();
            }
        }
    }failure:^(AFHTTPRequestOperation *operation,NSError *error){
        NSLog(@"我的好友刷新网络终断");
    }];
}


- (void)getApplyListwithComepletion:(CompletionBlock)completionBlock
{
    NSString *url = [PPAPIList getAPIList].PPQueryRequestList;
    NSDictionary *params = @{@"userId":@(self.userInfo.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation , id responseObject){
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            //返回成功
            [self.applyArray removeAllObjects];
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSArray *requestList = resultMap[@"requestList"];
            self.applyArray = [PPApplyNotification arrayOfModelsFromDictionaries:requestList];
            NSLog(@"我的申请已经刷新");
            if (completionBlock) {
                completionBlock();
            }
        }
    }failure:^(AFHTTPRequestOperation *operation,NSError *error){
        NSLog(@"我的申请刷新网络终断");
    }];
}


- (void)getConversationListwithComepletion:(CompletionBlock)completionBlock
{
    NSString *url = [PPAPIList getAPIList].PPQueryConversation;
    NSDictionary *params = @{@"userId":@(self.userInfo.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation , id responseObject){
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            //返回成功
            [self.conversationArray removeAllObjects];
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSArray *conversationList = resultMap[@"conversationList"];
            self.conversationArray = [PPConversation arrayOfModelsFromDictionaries:conversationList];
            //排序
            for (PPConversation *conversation in self.conversationArray) {
                conversation.conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:conversation.targetId isGroup:conversation.isGroup];
            }
            NSArray* sorte = [self.conversationArray sortedArrayUsingComparator:^NSComparisonResult(PPConversation *conversation1, PPConversation* conversation2){
                EMMessage *message1 = [conversation1.conversation latestMessage];
                EMMessage *message2 = [conversation2.conversation latestMessage];
                if(message1.timestamp > message2.timestamp) {
                    return (NSComparisonResult)NSOrderedAscending;
                }else {
                    return (NSComparisonResult)NSOrderedDescending;
                }
            }];
            NSMutableArray *resultArray = [[NSMutableArray alloc] initWithArray:sorte];
            self.conversationArray = [resultArray mutableCopy];
            NSLog(@"我的会话已经刷新");
            if (completionBlock) {
                completionBlock();
            }
        }
    }failure:^(AFHTTPRequestOperation *operation,NSError *error){
        NSLog(@"我的会话刷新网络终断");
    }];
}


- (void)getPetListwithComepletion:(CompletionBlock)completionBlock
{
    NSString *url = [PPAPIList getAPIList].PPQueryPetMsgByUserId;
    NSDictionary *params = @{@"userId":@(self.userInfo.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation , id responseObject){
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            //返回成功
            [self.petsArray removeAllObjects];
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSArray *petList = resultMap[@"petList"];
            self.petsArray = [PPPetInfo arrayOfModelsFromDictionaries:petList];
            NSLog(@"我的宠物已经刷新");
            if (completionBlock) {
                completionBlock();
            }
        }
    }failure:^(AFHTTPRequestOperation *operation,NSError *error){
        NSLog(@"我的宠物刷新网络终断");
    }];
}


- (void)getTopicListwithComepletion:(CompletionBlock)completionBlock
{
    NSString *url = [PPAPIList getAPIList].PPQueryTopicMsgByUserId;
    NSDictionary *params = @{@"userId":@(self.userInfo.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation , id responseObject){
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            //返回成功
            [self.topicArray removeAllObjects];
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSArray *topicList = resultMap[@"topicList"];
            self.topicArray = [PPTopic arrayOfModelsFromDictionaries:topicList];
            NSLog(@"我的话题已经刷新");
            if (completionBlock) {
                completionBlock();
            }
        }
    }failure:^(AFHTTPRequestOperation *operation,NSError *error){
        NSLog(@"我的话题刷新网络终断");
    }];
}

- (void)getCirclePushListwithCompletion:(CompletionBlock)completionBlock
{
    NSString *url = [PPAPIList getAPIList].PPQueryUserCirclePush;
    NSDictionary *params = @{@"userId":@(self.userInfo.id),@"type":@(0)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation , id responseObject){
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            //返回成功
            [self.circleArray removeAllObjects];
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSArray *circlePushList = resultMap[@"circlePushList"];
            self.circleArray = [PPCirclePush arrayOfModelsFromDictionaries:circlePushList];
            NSLog(@"我的消息已经刷新");
            if (completionBlock) {
                completionBlock();
            }
        }
    }failure:^(AFHTTPRequestOperation *operation,NSError *error){
        NSLog(@"我的消息刷新网络终断");
    }];
}

- (void)getKeyWord
{
    NSString *url = [PPAPIList getAPIList].PPQueryKeyword;
    [httpRequst POST:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            //返回成功
            [self.keywordArray removeAllObjects];
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSArray *keyWordList = resultMap[@"keywordList"];
            for (NSDictionary *keywordDic in keyWordList) {
                NSString *keyword = keywordDic[@"keyword"];
                [self.keywordArray addObject:keyword];
            }
            NSLog(@"获得官方关键字");
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"获取关键字网络终断");
    }];
}

- (void)getOfficeTopic
{
    NSString *url = [PPAPIList getAPIList].PPQueryOfficeTopic;
    [httpRequst POST:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            //返回成功
            NSError *err = nil;
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSDictionary *topicDic = resultMap[@"topic"];
            self.officeTopic = [[PPTopic alloc] initWithDictionary:topicDic error:&err];

            NSLog(@"获得官方置顶贴");
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"获获得官方置顶贴网络终断");
    }];
}


@end
